package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.dao.SkuMapper;
import com.qingcheng.dao.StockBackMapper;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.StockBack;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.goods.StockBackService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service(interfaceClass = StockBackService.class)
public class StockBackServiceImpl implements StockBackService {
    @Autowired
    private StockBackMapper stockBackMapper;

    /**
     *
     * 添加缓冲回滚信息
     * @param orderItemList
     */
    @Transactional
    @Override
    public void addList(List<OrderItem> orderItemList) {
        //循环列表添加信息
        for (OrderItem orderItem : orderItemList) {
            StockBack stockBack = new StockBack();
            stockBack.setOrderId(orderItem.getOrderId());
            stockBack.setSkuId(orderItem.getSkuId());
            stockBack.setCreateTime(new Date());
            stockBack.setNum(orderItem.getNum());
            stockBack.setStatus("0");


            stockBackMapper.insertSelective(stockBack);
        }
    }

    @Autowired
    private SkuMapper skuMapper;
    /**
     * 回滚事务
     */
    @Override
    @Transactional
    public void doBack() {
        //获取回滚事务表中的状态为0的信息
        System.out.println("回滚任务开始");
        StockBack stockBack=new StockBack();
        stockBack.setStatus("0");
        List<StockBack> stockBackList = stockBackMapper.select(stockBack);
        //循环列表
        for (StockBack stockBack1 : stockBackList) {
            //增加库存
            skuMapper.deductionStock(stockBack1.getSkuId(),-stockBack1.getNum());

            //减少销量
            skuMapper.addSaleNum(stockBack1.getSkuId(),-stockBack1.getNum());
            //修改状态
            stockBack1.setStatus("1");
            stockBack1.setBackTime(new Date());
            stockBackMapper.updateByPrimaryKeySelective(stockBack1);
        }
        System.out.println("回滚任务结束");
    }



}
